package ru.brostudios.cosmicdonutlivewallpapers;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Random;
import javax.microedition.khronos.opengles.GL10;

public class Donut {

	private int width, height;
	private Texture texture;
	private FloatBuffer floatBuffer;
	private float scale;
	private float angle;
	private float x, y;
	private float vx, vy;
	
	public Donut(Texture texture, int x, int y, float scale, int width, int height) {
		this.width = width;
		this.height = height;
		this.texture = texture;
		floatBuffer = ByteBuffer.allocateDirect(4*4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();
		floatBuffer.put(new float[] {
			-texture.width/2.0f, +texture.height/2.0f, 0.0f, 0.0f,
			-texture.width/2.0f, -texture.height/2.0f, 0.0f, 1.0f,
			+texture.width/2.0f, +texture.height/2.0f, 1.0f, 0.0f,
			+texture.width/2.0f, -texture.height/2.0f, 1.0f, 1.0f
		});
		this.x = x;
		this.y = y;
		this.scale = scale;
		Random rnd = new Random();
		angle = rnd.nextInt(360);
		vx = (rnd.nextFloat() - 0.5f)/2;
		vy = (rnd.nextFloat() - 0.5f)/2;
	}
	
	public void Draw(GL10 gl) {
		gl.glEnable(GL10.GL_TEXTURE_2D);
		gl.glEnable(GL10.GL_BLEND);
		gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
		gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
		floatBuffer.position(0);
		gl.glVertexPointer(2, GL10.GL_FLOAT, 4*4, floatBuffer);
		gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		floatBuffer.position(2);
		gl.glTexCoordPointer(2, GL10.GL_FLOAT, 4*4, floatBuffer);
		gl.glMatrixMode(GL10.GL_MODELVIEW);
		gl.glPushMatrix();
		gl.glLoadIdentity();
		gl.glTranslatef((float)x, (float)y, 0);
		gl.glRotatef(angle, 0.0f, 0.0f, 1.0f);
		gl.glScalef(scale, scale, 1.0f);
		gl.glBindTexture(GL10.GL_TEXTURE_2D, texture.glid);
		gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, 4);
		gl.glPopMatrix();
		gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
		gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
		gl.glDisable(GL10.GL_BLEND);
		gl.glDisable(GL10.GL_TEXTURE_2D);
	}
	
	public void Update() {
		angle += 0.3f;
		x += vx;
		y += vy;
		if((x+texture.width*scale)<(-width/2) || (x-texture.width*scale)>(width/2) ||
		   (y+texture.height*scale)<(-height/2) || (y-texture.height*scale)>(height/2)) {
			Random rnd = new Random();
			if(x >= 0) vx = -(rnd.nextFloat()/4);
			else vx = rnd.nextFloat()/4;
			if(y >= 0) vy = -(rnd.nextFloat()/4);
			else vy = rnd.nextFloat()/4;
		}
	}
	
	public void ChangeTexture(Texture texture) {
		this.texture = texture;
	}
	
}